// service-worker.js

// 缓存的静态资源
const cacheName = 'my-cache-v1'
const staticAssets = [
  '/',
  '/index.html',
  '/styles.css',
  '/script.js',
  '/image.png',
]

// 安装 Service Worker
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(cacheName)
      .then(cache => {
        const cachePromises = staticAssets.map(url => {
          return fetch(url).then(response => {
            if (!response.ok) {
              throw new Error(`${url} 请求失败`)
            }
            return cache.put(url, response)
          })
        })

        return Promise.all(cachePromises)
      })
      .then(() => {
        console.log('Service Worker 安装成功')
      })
      .catch(error => {
        console.log('Service Worker 安装失败:', error)
      })
  )
})

// 激活 Service Worker
self.addEventListener('activate', event => {
  console.log('activate')
  event.waitUntil(
    caches.keys()
      .then(cacheNames => {
        return Promise.all(
          cacheNames.filter(name => name !== cacheName)
            .map(name => caches.delete(name))
        )
      })
  )
})

// 捕获请求并返回缓存的资源
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        console.log('response', response)
        if (response) return response

        return fetch(event.request).then(serverResponse => {
          console.log('serverResponse')
          // 复制一份新的响应对象
          const clonedResponse = serverResponse.clone()

          // 将新的响应添加到缓存中，以便下次使用
          caches.open(cacheName).then(cache => {
            cache.put(event.request, clonedResponse)
          })

          // 返回新的响应给页面
          return serverResponse
        })
      })
  )
})
